# -*- coding: UTF-8 -*-
import yaml
import os
from tools.handle_path import config_path

PAR_CONFIG = os.path.join(config_path, 'params_config.yaml')
DATA_SOURCE_CONFIG = os.path.join(config_path, 'data_source_config.yaml')


class YamlReader:
    """
    读取YAML数据
    @:param file_path 文件路径
    @:return
    """

    def __init__(self, file_path):
        # 如果路径文件存在
        if os.path.exists(file_path):
            self.file_path = file_path
        else:
            raise FileNotFoundError('FileNotFound')
        self._data = None

    def data(self):
        if not self._data:
            with open(self.file_path, 'rb') as f:
                self._data = list(yaml.safe_load_all(f))
            return self._data

    def get(self, element, index=0):
        try:
            return self.data()[index].get(element)
        except Exception as e:
            return e

    def get_yaml_data(self, key=None):
        with open(self.file_path, encoding="utf-8") as f:
            yaml_data = yaml.safe_load(f.read())
            if key:
                yaml_data = yaml_data.get(key)
        return yaml_data


if __name__ == "__main__":
    r = YamlReader(file_path=DATA_SOURCE_CONFIG).get_yaml_data()
    print(r.keys())
